package com.arthur.controller;

import com.arthur.bean.User;
import com.arthur.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller
@MultipartConfig
public class RegisterController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @RequestMapping("/RegisterController")
    @ResponseBody
    protected Map fetchUserinfo(HttpServletRequest request, @RequestParam("myfile") MultipartFile file)
            throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String userpwd = request.getParameter("userpwd");

		//增加上传功能
		// 1、 将文件保存到tomcat服务器所在盘符的指定目录下
		// 1.1得到服务器所在的盘符
		String uploadPath = request.getSession().getServletContext().getRealPath(".");
        System.out.println("uploadPath>>>"+uploadPath);
        System.out.println("File.separator>>>"+File.separator);
		int endIndex = uploadPath.indexOf(File.separator) + 1;
		uploadPath = uploadPath.substring(0, endIndex);
		System.out.println("uploadPath:"+uploadPath);

		// 2.2在该盘符下创建images的上传文件夹
		File uploadFileFolder = new File(uploadPath + "/images");
		if (!uploadFileFolder.exists()) {
			uploadFileFolder.mkdirs();
		}

		// 2获取并保存文件
        //1 获取上传的文件
        if(!file.isEmpty()){
            //System.out.println(uploadFileFolder.getAbsolutePath());
            file.transferTo(new File(uploadFileFolder.getAbsolutePath()+"\\"+file.getOriginalFilename()));
        }

		//2.4 定义保存到数据库的图片路径
		String imgpath="images/"+file.getOriginalFilename();

        User user = new User();
        user.setUsername(username);
        user.setUserpwd(userpwd);
        user.setImgpath(imgpath);

        int count = userService.registerByUserinfo(user);

        if (count == 1) {
            objectMap.put("result", "1");
        } else {
            objectMap.put("result", "0");
        }
        return objectMap;
    }

}
